﻿using PAP.Application.CommandHandlers.Resources;
using PAP.Application.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PAP.Application.CommandHandlers
{
    public abstract class CommandHandler<TCommand> : ICommandHandler<TCommand>
        where TCommand : ICommand
    {
        #region "Fields"
        protected readonly IUnitOfWork _unitOfWork;
        #endregion

        #region "Constructors"
        public CommandHandler(IUnitOfWork unitOfWork)
        {
            this._unitOfWork = unitOfWork;
        }
        #endregion

        public void Handle(TCommand command)
        {
            if (command == null)
            {
                throw new ArgumentException(Messages.CommandIsNull);
            }

            Execute(command);
            this._unitOfWork.Commit();
        }

        protected abstract void Execute(TCommand command);
    }

    public abstract class CommandHandler<TCommand,TResponse> : ICommandHandler<TCommand,TResponse>
        where TCommand : ICommand
        where TResponse : IResponse
    {
        #region "Fields"
        protected readonly IUnitOfWork _unitOfWork;
        #endregion

        #region "Constructors"
        public CommandHandler(IUnitOfWork unitOfWork)
        {
            this._unitOfWork = unitOfWork;
        }
        #endregion

        public TResponse Handle(TCommand command)
        {
            if (command == null)
            {
                throw new ArgumentException(Messages.CommandIsNull);
            }

            var response = Execute(command);
            this._unitOfWork.Commit();
            return response;
        }

        protected abstract TResponse Execute(TCommand command);
    }
}
